package 字符串系列;

public class ReplaceSpace {
    //解法一：定义StringBuffer对象
    public String replaceSpace(String s) {
        char[] ans = s.toCharArray();
        System.out.println(ans);
        StringBuffer result = new StringBuffer();
        for(char c : ans){
            System.out.println((int)c);
            if (c-'a'==32){
                result.append("%20");
            }else{
                result.append(c);
            }
        }
        s = result.toString();
        return s;
    }
    //解法二，双指针法
    public String replaceSpace1(String s) {
        if(s==null || s.length()==0){
            return s;
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == ' '){
                sb.append("  ");
            }
        }
        //若是没有空格直接返回
        if(sb.length() == 0){
            return s;
        }
        //有空格情况 定义两个指针
        int left = s.length() - 1;  //左指针：指向原始字符串最后一个位置
        s += sb.toString();
        int right= s.length() - 1;  //右指针：指向扩展字符串的最后一个位置
        char[] chars = s.toCharArray();
        while (left>=0){
            if(chars[left] == ' '){
                chars[right--] = '0';
                chars[right--] = '2';
                chars[right] = '%';
            }else{
                chars[right] = chars[left];
            }
            left--;
            right--;
        }
        return new String(chars);
    }

    //解法三
    public String replaceSpace2(String s) {
        int length = s.length();
        char[] array = new char[length * 3];    //按最多的扩充，最大为原数组的三倍
        int size = 0;   //size为最后的大小
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == ' ') {//碰到空格就往array数组里面加%20
                array[size++] = '%';
                array[size++] = '2';
                array[size++] = '0';
            } else {    //否则就加c
                array[size++] = c;
            }
        }
        String newStr = new String(array, 0, size); //保存结果
        return newStr;
    }




}
